<template>
  <div style="text-align: center">
    <el-breadcrumb separator-class="el-icon-arrow-right" class="myColor">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home/equipment' }">设备监控</el-breadcrumb-item>
      <el-breadcrumb-item>设备主动运维计划</el-breadcrumb-item>
    </el-breadcrumb>
    <el-container>
      <el-select v-model="value" value-key="id" filterable placeholder="请选择打磨产线"
                 @change="handleNodeClick($event)" z-index:2>
        <el-option width="100px"
             v-for="item in LineList"
            :key="item.id"
            :label="item.label"
            :value="item"
            :props="defaultProps"
            default-expand-all
          >
        </el-option>
      </el-select>
      <div v-if="showHello" style="z-index: 2">
        <el-form :inline="true" :model="formInline"
                 style="position: absolute;margin-top: 20px;margin-left: 50%">
          <el-form-item label="选择运维时间范围" style="position: absolute;
          top: 50px;left: -660px">
            <el-date-picker
              v-model="formInline.time"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="width: 500px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" style="position: absolute;margin-top: 100px;margin-left: 50%">
            <el-checkbox-group v-model="formInline.type"
                               style="position: absolute;left: -660px">
              <el-checkbox label="1">日常保养</el-checkbox>
              <el-checkbox label="2" style="position: relative;left: 20px">一级保养</el-checkbox>
              <el-checkbox label="3" style="position: relative;left: 40px">二级保养</el-checkbox>
              <el-checkbox label="4" style="position: relative;left: 60px">大修</el-checkbox>
              <el-checkbox label="5" style="position: relative;left: 80px">检测故障</el-checkbox>
              <el-checkbox label="6" style="position: relative;left: 100px">突发故障</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item style="position:absolute;margin-left: 50%">
            <el-button type="primary" @click="onSubmit"
                       style="position: absolute;margin-top: 50px;left: -25px">查询</el-button>
            <el-button type="primary" plain @click="onSubmitAll"
                       style="position: absolute;
                         left: -660px;
                         width: 300px">显示全生命周期的运维活动</el-button>
            <el-button type="primary" plain
                       style="position: absolute;
                         left: -270px;
                         width: 300px">查看历史维护记录</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="showTable" :style="cardHeight">
        <el-form :inline="true" :model="formInline"
                 style="position: absolute;margin-top: 20px;margin-left: 50%">
          <el-form-item label="选择运维时间范围" style="position: absolute;
          top: 50px;left: -660px">
            <el-date-picker
              v-model="formInline.time"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="width: 500px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" style="position: absolute;margin-top: 100px;margin-left: 50%">
            <el-checkbox-group v-model="formInline.type"
                               style="position: absolute;left: -660px">
              <el-checkbox label="1">日常保养</el-checkbox>
              <el-checkbox label="2" style="position: relative;left: 20px">一级保养</el-checkbox>
              <el-checkbox label="3" style="position: relative;left: 40px">二级保养</el-checkbox>
              <el-checkbox label="4" style="position: relative;left: 60px">大修</el-checkbox>
              <el-checkbox label="5" style="position: relative;left: 80px">检测故障</el-checkbox>
              <el-checkbox label="6" style="position: relative;left: 100px">突发故障</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item style="position:absolute;margin-left: 50%">
            <el-button type="primary" @click="onSubmit"
                       style="position: absolute;margin-top: 50px;left: -25px">查询</el-button>
            <el-button type="primary" plain @click="onSubmitAll"
                       style="position: absolute;
                         left: -660px;
                         width: 300px">显示全生命周期的运维活动</el-button>
            <el-button type="primary" plain
                       style="position: absolute;
                         left: -270px;
                         width: 300px">查看历史维护记录</el-button>
          </el-form-item>
        </el-form>
        <el-main>
          <el-timeline>
           <el-timeline-item
            v-for="(node, index) in nodeData"
            :key="index"
            :timestamp="node.date"
            :color="node.color"
            size="large"
            :icon="node.icon"
            @click.native="clickNode(index)">
            <el-row>
              <el-card>
                <h4>{{ node.title }}</h4>
                <el-table
                  :data="node.table"
                  border
                  style="width: 100%">
                  <el-table-column
                    prop="system"
                    label="系统"
                    width="180">
                  </el-table-column>
                  <el-table-column
                    prop="part"
                    label="部件"
                    width="180">
                  </el-table-column>
                  <el-table-column
                    prop="item"
                    label="运维项目"
                    width="180">
                  </el-table-column>
                  <el-table-column
                    prop="consumable"
                    label="工具"
                    width="180">
                  </el-table-column>
                  <el-table-column
                    prop="method"
                    label="运维方法">
                  </el-table-column>
                  <el-table-column
                    prop="performance"
                    label="是否执行"
                    width="120">
                  </el-table-column>
                  <el-table-column
                    prop="user"
                    label="维修员"
                    width="120">
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    label="派工"
                    width="100">
                    <template slot-scope="scope">
                      <el-button
                        @click="showDispatchDialog(scope.row)"
                        v-if="scope.row.performance === '未执行运维'"
                        type="danger" plain>
                        派工</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-row>
          </el-timeline-item>
          </el-timeline>
        </el-main>
      </div>
    </el-container>
    <el-dialog title="生成每日运维计划"
               :visible.sync="planningDialogVisible">
      <el-form :model="planningForm" :rules="planningRules" ref="planningForm">
        <el-form-item label="设备名称" :label-width="formLabelWidth" prop="kneader">
          <el-input v-model="planningForm.kneader" autocomplete="off" :disabled="true"/>
        </el-form-item>
        <el-form-item label="活动时间" :label-width="formLabelWidth" prop="date">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="planningForm.date"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="运维年限" :label-width="formLabelWidth" prop="term">
          <el-input v-model.number="planningForm.term" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="planningDialogCancel('planningForm')">取 消</el-button>
        <el-button
          type="primary"
          v-loading.fullscreen.lock="fullscreenLoading"
          element-loading-text="正在生成设备全生命周期运维计划，请勿关闭页面"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          @click="planningDialogConfirm('planningForm')">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog width="400px"
               style="position: absolute;top: 1%"
               :visible.sync="dispatchDialogVisible">
      <div slot="title" class="header-title" id="dialog_title">
        <div style="padding:15px 20px">运维活动派工</div>
      </div>
      <div style="height: 300px">
        <el-cascader
          v-model="userName"
          :options="userOptions"
          style="width: 360px"
          :props="{ expandTrigger: 'hover' }"></el-cascader>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="dispatchDialogVisible = false">取 消</el-button>
        <el-button type="success" @click="dispatch">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script itemscope>
const dayjs = require('dayjs');

export default {
  name: 'Home',
  created() {
    this.resize();
    this.defaultForm();
  },
  mounted() {
    this.loadMachineList();
    this.loadUserList();
    window.addEventListener('resize', this.resize);
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
  },
  data() {
    return {
      dispatchData: {},
      dispatchID: null,
      dispatchDialogVisible: false,
      userName: '',
      userOptions: [],
      userList: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          },
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          },
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          },
        }],
      },
      formInline: {
        time: [],
        type: ['1', '2', '3', '4', '5', '6'],
      },
      formLabelWidth: '120px',
      planningForm: {
        line: '',
        date: '',
        term: null,
      },
      planningRules: {
        line: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        date: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        term: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { type: 'number', message: '年限必须为数字值' },
        ],
      },
      planningDialogVisible: false,
      fullscreenLoading: false,
      drawer: false,
      drawerData: {
        content: {},
      },
      cardHeight: {
        height: null,
      },
      nodeData: [],
      LineList: [],
      showTable: false,
      showHello: true,
      maintenance: [],
      value: '',
      tableHeight: null,
      filterText: '',
      LineID: null,
      LineName: '运维计划名称',
      defaultProps: {
        label: 'label',
      },
    };
  },
  methods: {
    dispatch() {
      const { axios, dispatchID } = this;
      const putData = this.dispatchData;
      putData.performance = false;
      // eslint-disable-next-line prefer-destructuring
      putData.user_id = this.userName[1];
      axios({
        method: 'put',
        url: `/equipment_maintenance_plan/maintenance_schedule_content/${dispatchID}/`,
        timeout: 600000,
        data: putData,
      })
        .then(() => {
          this.dispatchDialogVisible = false;
          this.$message({
            message: '派工成功！',
            type: 'success',
          });
          this.onSubmit();
        })
        .catch((error) => {
          console.log(error.response.data);
          this.$message.error('派工失败');
        });
    },
    showDispatchDialog(data) {
      console.log(data);
      this.dispatchDialogVisible = true;
      this.dispatchID = data.id;
      this.dispatchData = data;
    },
    defaultForm() {
      this.formInline.time[0] = dayjs();
      this.formInline.time[1] = dayjs().add(1, 'month');
      this.formInline.type = ['1', '2', '3', '4', '5', '6'];
    },
    onSubmit() {
      this.getTimelineData(
        this.formInline.type.toString(),
        dayjs(this.formInline.time[0]).format('YYYY-MM-DD'),
        dayjs(this.formInline.time[1]).format('YYYY-MM-DD'),
      );
    },
    onSubmitAll() {
      const a = this.formInline.type.filter((value) => value !== '1');
      this.formInline.type = a;
      this.getTimelineData(a.toString());
      this.formInline.time = [];
    },
    planningButton() {
      this.planningDialogVisible = true;
      this.planningForm.kneader = this.machineName;
    },
    planningDialogCancel(formName) {
      this.planningDialogVisible = false;
      this.$refs[formName].resetFields();
    },
    planningDialogConfirm(formName) {
      const {
        planningForm, axios, getTimelineData,
      } = this;
      const postData = planningForm;
      postData.kneader = this.machineID;
      this.fullscreenLoading = true;
      // eslint-disable-next-line consistent-return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios({
            method: 'post',
            url: '/equipment_maintenance_plan/maintenance_schedule/planning/',
            timeout: 100000000000000,
            data: postData,
          })
            .then((response) => {
              this.planningDialogVisible = false;
              this.fullscreenLoading = false;
              console.log(response);
              this.$message({
                message: '添加成功！',
                type: 'success',
              });
              getTimelineData();
            })
            .catch((error) => {
              console.log(error.response.data);
              this.$message.error('添加失败');
              this.fullscreenLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    clickNode(index) {
      console.log(index);
    },
    handleNodeClick(value) {
      this.LineID = value.id;
      this.LineName = value.label;
      this.showHello = false;
      this.showTable = true;
      this.defaultForm();
      this.onSubmit();
    },
    // 获取时间线的数据
    getTimelineData(typesList, timeRangeAfter, timRangeBefore) {
      const { axios } = this;
      this.nodeData = [];
      axios({
        method: 'get',
        url: '/equipment_maintenance_plan/maintenance_schedule_content/',
        params: {
          line_id: this.LineID,
          types_list: typesList,
          time_range_after: timeRangeAfter,
          time_range_before: timRangeBefore,
          ordering: 'datetime',
        },
        timeout: 600000,
      })
        .then((response) => {
          // eslint-disable-next-line no-restricted-syntax
          for (const item of response.data) {
            const i = {
              date: '',
              table: [{
                id: '',
                system: '',
                consumable: '',
                item: '',
                method: '',
                part: '',
                performance: '',
              }],
              title: '',
              color: '',
              size: 'large',
              icon: '',
            };
            if (item.types === 1) {
              i.date = dayjs(item.datetime).format('YYYY-MM-DD');
              i.title = '日常保养';
              i.color = 'rgba(157,29,210,0.5)';
              i.table[0].consumable = item.consumable;
              i.table[0].item = item.item;
              i.table[0].method = item.method;
              i.table[0].system = item.system;
              i.table[0].part = item.part;
              i.table[0].id = item.id;
              i.table[0].line_id = item.line_id;
              i.table[0].schedule = item.schedule;
              i.table[0].types = item.types;
              i.table[0].user = this.findUser(item.user_id);
              if (item.performance === true) {
                i.table[0].performance = '已经执行运维';
              } else {
                i.table[0].performance = '未执行运维';
              }
            } else if (item.types === 2) {
              i.date = dayjs(item.datetime).format('YYYY-MM-DD');
              i.title = '一级保养';
              i.color = '#64bd0a';
              i.table[0].consumable = item.consumable;
              i.table[0].item = item.item;
              i.table[0].method = item.method;
              i.table[0].system = item.system;
              i.table[0].part = item.part;
              i.table[0].id = item.id;
              i.table[0].line_id = item.line_id;
              i.table[0].schedule = item.schedule;
              i.table[0].types = item.types;
              i.table[0].user = this.findUser(item.user_id);
              if (item.performance === true) {
                i.table[0].performance = '已经执行运维';
              } else {
                i.table[0].performance = '未执行运维';
              }
            } else if (item.types === 3) {
              i.date = dayjs(item.datetime).format('YYYY-MM-DD');
              i.title = '二级保养';
              i.color = '#2e89c9';
              i.table[0].consumable = item.consumable;
              i.table[0].item = item.item;
              i.table[0].method = item.method;
              i.table[0].system = item.system;
              i.table[0].part = item.part;
              i.table[0].id = item.id;
              i.table[0].line_id = item.line_id;
              i.table[0].schedule = item.schedule;
              i.table[0].types = item.types;
              i.table[0].user = this.findUser(item.user_id);
              if (item.performance === true) {
                i.table[0].performance = '已经执行运维';
              } else {
                i.table[0].performance = '未执行运维';
              }
            } else if (item.types === 4) {
              i.date = dayjs(item.datetime).format('YYYY-MM-DD');
              i.title = '大修';
              i.color = '#6f7072';
              i.table[0].consumable = item.consumable;
              i.table[0].item = item.item;
              i.table[0].method = item.method;
              i.table[0].system = item.system;
              i.table[0].part = item.part;
              i.table[0].id = item.id;
              i.table[0].line_id = item.line_id;
              i.table[0].schedule = item.schedule;
              i.table[0].types = item.types;
              i.table[0].user = this.findUser(item.user_id);
              if (item.performance === true) {
                i.table[0].performance = '已经执行运维';
              } else {
                i.table[0].performance = '未执行运维';
              }
            } else if (item.types === 5) {
              i.date = dayjs(item.datetime).format('YYYY-MM-DD');
              i.title = '监测故障';
              i.color = '#ce7610';
              i.table[0].consumable = item.consumable;
              i.table[0].item = item.item;
              i.table[0].method = item.method;
              i.table[0].system = item.system;
              i.table[0].part = item.part;
              i.table[0].id = item.id;
              i.table[0].line_id = item.line_id;
              i.table[0].schedule = item.schedule;
              i.table[0].types = item.types;
              i.table[0].user = this.findUser(item.user_id);
              if (item.performance === true) {
                i.table[0].performance = '已经执行运维';
              } else {
                i.table[0].performance = '未执行运维';
              }
            } else if (item.types === 6) {
              i.date = dayjs(item.datetime).format('YYYY-MM-DD');
              i.title = '突发故障';
              i.color = '#da0000';
              i.table[0].consumable = item.consumable;
              i.table[0].item = item.item;
              i.table[0].method = item.method;
              i.table[0].system = item.system;
              i.table[0].part = item.part;
              i.table[0].id = item.id;
              i.table[0].line_id = item.line_id;
              i.table[0].schedule = item.schedule;
              i.table[0].types = item.types;
              i.table[0].user = this.findUser(item.user_id);
              if (item.performance === true) {
                i.table[0].performance = '已经执行运维';
              } else {
                i.table[0].performance = '未执行运维';
              }
            }
            this.nodeData.push(i);
          }
        });
    },
    // eslint-disable-next-line consistent-return
    findUser(id) {
      let name = '';
      // eslint-disable-next-line no-restricted-syntax,guard-for-in
      for (const item of this.userList) {
        if (id === item.user) {
          name = item.name;
        }
      }
      return name;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    loadUserList() {
      const { axios } = this;
      this.userList = [];
      this.groupList = [];
      this.userOptions = [];
      axios({
        method: 'get',
        url: '/home/employee/',
        timeout: 600000,
        params: {
          role: '设备维修员',
        },
      })
        .then((response) => {
          this.userList = response.data;
          const groupSet = new Set();
          // eslint-disable-next-line no-restricted-syntax
          for (const item of response.data) {
            groupSet.add(item.department);
          }
          // eslint-disable-next-line no-restricted-syntax
          for (const item of groupSet) {
            const a = {
              value: '',
              label: '',
              children: [],
            };
            a.value = item;
            a.label = item;
            // eslint-disable-next-line no-restricted-syntax
            for (const j of response.data) {
              if (j.department === item) {
                const b = {
                  value: '',
                  label: '',
                };
                b.value = j.user;
                b.label = j.name;
                a.children.push(b);
              }
            }
            this.userOptions.push(a);
          }
        });
    },
    loadMachineList() {
      const { axios } = this;
      const LineItem = [];
      this.LineList = [];
      axios({
        method: 'get',
        url: '/equipment_maintenance_plan/polish_line/',
        timeout: 600000,
      })
        .then((response) => {
          // eslint-disable-next-line no-restricted-syntax
          for (const item of response.data) {
            const i = {
              id: null,
              label: '',
            };
            i.id = item.line_id;
            i.label = item.line_name;
            LineItem.push(i);
          }
        });
      this.LineList = LineItem;
    },
    resize() {
      this.tableHeight = window.innerHeight - 200;
      this.cardHeight.height = `${this.tableHeight}px`;
    },
  },
};
</script>

<style scoped lang="scss">

.el-header {
  background-color: #409EFF;
  color: #FFFFFF;
  line-height: 60px;
  font-size: x-large;
  -webkit-user-select: none;
}

#menu {
  text-align: center;
  margin-top: -2px;
  position: fixed;
  right: 20px;
}

.import {
  text-align: center;
  margin-top: -2px;
}

.el-aside {
  border-right: 1px solid #E6E6E6;
}

.el-main {
  position: absolute;
  top: 260px;
  left: 17%;
  padding-bottom: 30px;
  height: 60%;
  width: 80%;
  z-index: 1;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: aliceblue;
  color: #333;
  text-align: center;
}

.el-dropdown-link {
  cursor: pointer;
  color: #FFFFFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.softwareCard {
  margin-top: 4px;
  text-align: center;
}

.buttonGroup {
  position: fixed;
  bottom: 60px;
  padding: 10px 17px;
  //background-color: #409EFF;
}

.tableTitle {
  margin-bottom: 10px;
}

.el-tree /deep/ .is-current > .el-tree-node__content {
  background: #409EFF !important;
  color: #fff !important;
}

.myColor /deep/ .el-breadcrumb__inner {
  color:  #409EFF ;
  height: 100%;
}

.el-breadcrumb{
  font-size: 16px;
  width: 150%;
  position: relative;
  margin-top: 10px;
}

.el-select{
  position: relative;
  margin-top: 20px;
  margin-left: -5px;
  z-index: 2;
}

#dialog_title{
  color: #409EFF;
  border: 5px;
  font-size: 20px;
}
</style>
